import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

/**
 * 游戏管理工具
 * 统一处理所有游戏相关操作的核心工具
 */
export const gameManagementTool = createTool({
  id: 'game-management',
  description: '统一的游戏管理工具，处理案件生成、对话、推理评估等所有游戏操作',
  inputSchema: z.object({
    action: z.enum([
      'start_game',
      'chat_with_suspect', 
      'submit_deduction',
      'get_game_status',
      'update_game_state'
    ]).describe('要执行的操作类型'),
    
    // 开始游戏参数
    difficulty: z.enum(['easy', 'normal', 'hard']).optional().describe('游戏难度'),
    theme: z.string().optional().describe('案件主题'),
    suspectCount: z.number().optional().describe('嫌疑人数量'),
    
    // 对话参数
    gameId: z.string().optional().describe('游戏ID'),
    suspectId: z.string().optional().describe('嫌疑人ID'),
    question: z.string().optional().describe('玩家问题'),
    conversationHistory: z.array(z.any()).optional().describe('对话历史'),
    
    // 推理提交参数
    culpritId: z.string().optional().describe('玩家选择的真凶ID'),
    reasoning: z.string().optional().describe('推理过程'),
    evidence: z.array(z.string()).optional().describe('支持证据'),
    
    // 其他参数
    params: z.record(z.any()).optional().describe('其他操作参数')
  }),
  outputSchema: z.object({
    success: z.boolean().describe('操作是否成功'),
    message: z.string().describe('操作结果消息'),
    data: z.any().optional().describe('返回的数据'),
    gameState: z.any().optional().describe('游戏状态'),
    error: z.string().optional().describe('错误信息')
  }),
  execute: async ({ context }) => {
    const { action, ...params } = context;
    
    try {
      console.log(`执行游戏操作: ${action}`, params);
      
      switch (action) {
        case 'start_game':
          return await handleStartGame(params);
          
        case 'chat_with_suspect':
          return await handleChatWithSuspect(params);
          
        case 'submit_deduction':
          return await handleSubmitDeduction(params);
          
        case 'get_game_status':
          return await handleGetGameStatus(params);
          
        case 'update_game_state':
          return await handleUpdateGameState(params);
          
        default:
          return {
            success: false,
            message: `未知的操作类型: ${action}`,
            error: 'UNKNOWN_ACTION'
          };
      }
    } catch (error) {
      console.error(`游戏操作失败 [${action}]:`, error);
      return {
        success: false,
        message: `操作失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: error instanceof Error ? error.message : 'UNKNOWN_ERROR'
      };
    }
  },
});

/**
 * 处理开始新游戏
 */
async function handleStartGame(params: any) {
  const { difficulty = 'normal', theme, suspectCount = 3 } = params;
  
  try {
    console.log('开始生成新案件...');

    // 生成游戏ID
    const gameId = `game-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

    // 动态导入并调用案件生成Agent
    const { generateCase } = await import('../agents/case-generator.agent');
    const caseData = await generateCase(difficulty, theme, suspectCount);
    
    // 构建游戏状态
    const gameState = {
      gameId,
      caseId: caseData.case.id,
      phase: 'investigation',
      timeRemaining: 180, // 3分钟
      discoveredClues: caseData.initialClues?.filter((clue: any) => clue.isRevealed).map((clue: any) => clue.id) || [],
      conversationCount: 0,
      suspectInteractions: {},
      score: 0,
      startTime: new Date().toISOString()
    };
    
    // 过滤敏感信息
    const publicCaseData = {
      case: caseData.case,
      suspects: caseData.suspects?.map((suspect: any) => ({
        ...suspect,
        secrets: undefined,
        isCulprit: undefined,
      })) || [],
      initialClues: caseData.initialClues?.filter((clue: any) => clue.isRevealed) || []
    };
    
    console.log('案件生成成功:', caseData.case.title);
    
    return {
      success: true,
      message: '新游戏开始成功',
      data: {
        gameId,
        caseData: publicCaseData,
        gameState
      },
      gameState
    };
    
  } catch (error) {
    console.error('开始新游戏失败:', error);
    
    // 降级方案：使用模拟数据
    const mockGameId = `game-${Date.now()}-mock`;
    const mockCaseData = {
      case: {
        id: `case-${Date.now()}`,
        title: '办公室咖啡毒杀案',
        description: '张经理在办公室喝咖啡后突然倒地身亡，初步检查发现咖啡中含有氰化物',
        location: '科技公司办公室',
        timeOfCrime: '上午10:30',
        victim: '张经理',
        murderWeapon: '氰化物',
        motive: '升职竞争',
        culpritId: 'suspect-2',
        difficulty,
        createdAt: new Date().toISOString()
      },
      suspects: [
        {
          id: 'suspect-1',
          name: '李助理',
          personality: '谨慎内向',
          background: '新入职员工，渴望证明自己',
          alibi: '在会议室整理文件',
          suspicionLevel: 3
        },
        {
          id: 'suspect-2', 
          name: '王同事',
          personality: '野心勃勃',
          background: '竞争对手，一直想要张经理的职位',
          alibi: '在洗手间',
          suspicionLevel: 7
        },
        {
          id: 'suspect-3',
          name: '陈清洁工',
          personality: '老实本分',
          background: '长期员工，知道很多公司秘密',
          alibi: '在打扫其他楼层',
          suspicionLevel: 2
        }
      ],
      initialClues: [
        {
          id: 'clue-1',
          description: '咖啡杯上有指纹',
          type: 'physical',
          importance: 4,
          isRevealed: true
        }
      ]
    };
    
    const mockGameState = {
      gameId: mockGameId,
      caseId: mockCaseData.case.id,
      phase: 'investigation',
      timeRemaining: 180,
      discoveredClues: ['clue-1'],
      conversationCount: 0,
      suspectInteractions: {},
      score: 0,
      startTime: new Date().toISOString()
    };
    
    return {
      success: true,
      message: '使用模拟数据开始游戏',
      data: {
        gameId: mockGameId,
        caseData: mockCaseData,
        gameState: mockGameState
      },
      gameState: mockGameState
    };
  }
}

/**
 * 处理与嫌疑人对话
 */
async function handleChatWithSuspect(params: any) {
  const { gameId, suspectId, question, conversationHistory = [] } = params;
  
  if (!gameId || !suspectId || !question) {
    return {
      success: false,
      message: '缺少必要参数：gameId, suspectId, question',
      error: 'MISSING_PARAMETERS'
    };
  }
  
  try {
    // 动态导入并调用嫌疑人对话Agent
    const { chatWithSuspectAgent } = await import('../agents/suspect.agent');
    const response = await chatWithSuspectAgent(gameId, suspectId, question, conversationHistory);
    
    return {
      success: true,
      message: '对话成功',
      data: {
        response: response.content,
        emotion: response.emotion,
        suspicionLevel: response.suspicionLevel,
        newClues: response.newClues || [],
        hints: response.hints || []
      }
    };
    
  } catch (error) {
    console.error('对话失败:', error);
    
    // 降级方案
    const mockResponses = [
      '我当时确实在现场，但我没有做任何可疑的事情。',
      '这个问题很难回答，我需要仔细想想。',
      '我觉得你应该去问问其他人，他们可能知道更多。'
    ];
    
    return {
      success: true,
      message: '对话成功（使用模拟回应）',
      data: {
        response: mockResponses[Math.floor(Math.random() * mockResponses.length)],
        emotion: 'nervous',
        suspicionLevel: Math.floor(Math.random() * 10) + 1,
        newClues: [],
        hints: []
      }
    };
  }
}

/**
 * 处理推理提交
 */
async function handleSubmitDeduction(params: any) {
  const { gameId, culpritId, reasoning, evidence = [] } = params;
  
  if (!gameId || !culpritId) {
    return {
      success: false,
      message: '缺少必要参数：gameId, culpritId',
      error: 'MISSING_PARAMETERS'
    };
  }
  
  // 这里应该从数据库获取真实答案，现在使用模拟数据
  const correctCulpritId = 'suspect-2'; // 模拟的正确答案
  const isCorrect = culpritId === correctCulpritId;
  
  const score = isCorrect ? 100 : 0;
  
  return {
    success: true,
    message: isCorrect ? '推理正确！' : '推理错误！',
    data: {
      isCorrect,
      score,
      correctCulprit: correctCulpritId,
      explanation: isCorrect 
        ? '恭喜！你成功找出了真凶。' 
        : `很遗憾，真凶是 ${correctCulpritId}。再接再厉！`
    }
  };
}

/**
 * 处理获取游戏状态
 */
async function handleGetGameStatus(params: any) {
  const { gameId } = params;
  
  if (!gameId) {
    return {
      success: false,
      message: '缺少游戏ID',
      error: 'MISSING_GAME_ID'
    };
  }
  
  // 这里应该从数据库获取游戏状态，现在返回模拟数据
  const mockGameState = {
    gameId,
    phase: 'investigation',
    timeRemaining: 120,
    discoveredClues: ['clue-1'],
    conversationCount: 2,
    suspectInteractions: {
      'suspect-1': 1,
      'suspect-2': 1
    },
    score: 0
  };
  
  return {
    success: true,
    message: '获取游戏状态成功',
    data: mockGameState,
    gameState: mockGameState
  };
}

/**
 * 处理更新游戏状态
 */
async function handleUpdateGameState(params: any) {
  const { gameId, updates } = params;
  
  if (!gameId || !updates) {
    return {
      success: false,
      message: '缺少必要参数：gameId, updates',
      error: 'MISSING_PARAMETERS'
    };
  }
  
  // 这里应该更新数据库中的游戏状态
  console.log('更新游戏状态:', gameId, updates);
  
  return {
    success: true,
    message: '游戏状态更新成功',
    data: updates
  };
}
